<template>
  <div>
    <van-popup
      round
      v-model:show="show"
      position="bottom"
      :close-on-click-overlay="true"
    >
      <div class="popup-box">
        <ul>
          <li
            class="item"
            v-for="item in operationList"
            :key="item.value"
            @click="handleOperationSelect(item)"
          >
            {{ item.text }}
          </li>
        </ul>
      </div>
    </van-popup>
		<SubEditPopup ref="subEditPopupRef" :item="info" :uid="info?.Id || null" :listData="listData" @update="updateData"/>

  </div>
</template>
<script setup lang="ts">
import SubEditPopup from "./sub-edit-popup.vue";
import { showDialog, showSuccessToast } from 'vant';
import { reqGoogleSecretReset } from "@/api/main";
import { reqUserSubAccountsDel} from "@/api/user";

const props = withDefaults(
	defineProps<{
		info: SubAccountMo | null;
    listData: any
	}>(),
	{}
);
const emit = defineEmits<{
  (event: "update"): void;
}>();
const show = ref(false);
const operationList = ref([
  { text: "编辑", value: "edit" },
  { text: "重置二次验证", value: "reset" },
  { text: "删除", value: "delete" },
]);
const subEditPopupRef = ref()

const handleOperationSelect = (item: { text: string; value: string }) => {
  switch (item.value) {
    case "edit":
      handleOperate(true)
      break;
    case "reset":
      handleReset()
      break;
    case "delete":
      handleDel()
      break;
    default:
      break;
  }
};


const beforeClose: any = (action: string) => {
	return new Promise((resolve) => {
		// 这里处理确认和取消操作
		resolve(action === 'confirm' || action === 'cancel');
	});
};

const doConfirm = async (callback: Function, text: string) => {
	try {
		await showDialog({
			title: '提示',
			message: text,
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			beforeClose,
			showCancelButton: true
		});
		await callback();
	} catch (error) {
		console.log("操作被取消或失败", error);
	}
};

const handleReset = () => {
	doConfirm(async () => {
		if (!props.info?.Id) return
		await reqGoogleSecretReset({Id: props.info?.Id});
		showSuccessToast('重置成功')
		show.value = false
    emit('update')
	}, "是否【重置】该子账号二次验证？");
}

const handleDel = () => {
	doConfirm(async () => {
		if (!props.info?.Id) return
		await reqUserSubAccountsDel({Id: props.info?.Id});
		showSuccessToast('子账号删除成功')
		show.value = false
    emit('update')
	}, "是否进行【删除】操作?");
}

const handleOperate = (isEdit = false) => {
  return subEditPopupRef.value?.open(isEdit)
}

const updateData = () => {
  subEditPopupRef.value?.closed();
  show.value = false
  emit('update')
}

defineExpose({
  open() {
    show.value = true;
  },
  handleOperate
});
</script>
<style scoped>
.popup-box {
  @apply py-[5px];
}
.popup-box .item {
  @apply h-[50px] text-[14px] text-center leading-[50px] border-solid border-b-[1px] border-[#E4E4E4];
}
</style>
